package top.bug.blog.utils;

import com.upyun.RestManager;
import com.upyun.UpException;
import okhttp3.Response;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author <a href="https://github.com/jiusi66">九思.</a>
 * @email 10837907@qq.com
 * @from <a href="https://www.52bug.top">递归茶馆-www.52bug.top</a>
 * @description 又拍云工具类
 */
public final class UpYunUtil {
    /**
     * 配置参数（可从配置类加载或直接读取）
     */
    private static String bucketName;
    private static String username;
    private static String password;
    private static String domain;

    /**
     * 延迟初始化的核心组件
     */
    private static volatile RestManager restManager;
    private static final ReentrantLock INIT_LOCK = new ReentrantLock();

    /**
     * 禁止实例化
     */
    private UpYunUtil() {
    }

    /**
     * 配置初始化方法（由Spring调用一次）
     */
    public static void initConfig(String bucket, String user, String pwd, String domainUrl) {
        bucketName = bucket;
        username = user;
        password = pwd;
        domain = domainUrl.endsWith(StrUtils.SLASH) ? domainUrl : domainUrl + StrUtils.SLASH;
    }

    /**
     * 上传文件（线程安全）
     */
    public static String upload(MultipartFile file, String filePath) throws IOException, UpException {
        ensureInitialized();
        String fileName = generateFileName(file.getOriginalFilename());
        String fullPath = buildFullPath(filePath, fileName);

        Map<String, String> params = new HashMap<>(1);
        params.put(RestManager.PARAMS.CONTENT_TYPE.getValue(), file.getContentType());

        try (Response response = restManager.writeFile(fullPath, file.getBytes(), params)) {
            if (response.isSuccessful()) {
                return domain + fullPath.replace(File.separator, StrUtils.SLASH);
            }
            throw new IOException("上传文件失败: " + response.message());
        }
    }

    /**
     * 删除文件
     */
    public static boolean delete(String filePath) throws IOException, UpException {
        ensureInitialized();
        try (Response response = restManager.deleteFile(filePath, null)) {
            return response.isSuccessful();
        }
    }

    /**
     * 删除文件夹
     *
     * @param dirPath 文件夹
     */
    public static boolean delDir(String dirPath) throws IOException, UpException {
        ensureInitialized();
        try (Response response = restManager.rmDir(dirPath)) {
            return response.isSuccessful();
        }
    }

    /**
     * 私有方法：延迟初始化RestManager
     */
    private static void ensureInitialized() {
        if (restManager == null) {
            INIT_LOCK.lock();
            try {
                if (restManager == null) {
                    restManager = new RestManager(bucketName, username, password);
                }
            } finally {
                INIT_LOCK.unlock();
            }
        }
    }

    /**
     * 生成唯一文件名
     */
    private static String generateFileName(String originalName) {
        String ext = originalName.substring(originalName.lastIndexOf(StrUtils.DOT));
        return UUID.randomUUID().toString().replace(StrUtils.DASHED, "") + ext;
    }

    /**
     * 构建完整路径
     */
    private static String buildFullPath(String filePath, String fileName) {
        if (filePath.isEmpty()) {
            return fileName;
        }
        if (!filePath.endsWith(StrUtils.SLASH)) {
            filePath += StrUtils.SLASH;
        }
        return filePath + fileName;
    }
}